<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
            </div>
          </template>
          <div class="profile-info">
            <div class="avatar-section">
              <el-avatar :size="80" :src="userInfo.avatar || defaultAvatar" />
              <div class="user-name">{{ userInfo.hm || '用户' }}</div>
              <div class="user-role">
                <el-tag :type="getRoleTagType(userInfo.roleValue)">
                  {{ userInfo.role || '用户' }}
                </el-tag>
              </div>
            </div>
            <div class="info-list">
              <div class="info-item">
                <span class="label">用户名：</span>
                <span class="value">{{ userInfo.hm || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">用户角色：</span>
                <span class="value">{{ userInfo.role || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">权限级别：</span>
                <span class="value">{{ getRoleDescription(userInfo.roleValue) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 修改密码卡片 -->
      <el-col :span="16">
        <el-card class="password-card">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>
          <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入当前密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
                修改密码
              </el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 个人设置卡片 -->
        <el-card v-if="showPersonalSettings" class="settings-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>个人设置</span>
            </div>
          </template>
          <el-form ref="settingsForm" :model="settingsForm" label-width="100px">
            <el-form-item label="邮箱地址">
              <el-input v-model="settingsForm.email" placeholder="请输入邮箱地址" />
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input v-model="settingsForm.phone" placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item label="个人简介">
              <el-input
                v-model="settingsForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入个人简介"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdateSettings" :loading="settingsLoading">
                保存设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作日志 -->
    <el-card v-if="showOperationLogs" class="log-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>最近操作日志</span>
        </div>
      </template>
      <el-table :data="operationLogs" stripe>
        <el-table-column prop="operation" label="操作" />
        <el-table-column prop="module" label="模块" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="ip" label="IP地址" />
        <el-table-column prop="createTime" label="操作时间" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
              {{ row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { useUserStore } from '@/stores/user'
import { userApi } from '@/api'

export default {
  name: 'Profile',
  setup() {
    const userStore = useUserStore()
    return { userStore }
  },
  data() {
    return {
      // 功能开关 - 控制是否显示某些功能模块
      showPersonalSettings: false,  // 个人设置功能开关
      showOperationLogs: false,     // 操作日志功能开关
      
      defaultAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      },
      settingsForm: {
        email: '',
        phone: '',
        description: ''
      },
      passwordLoading: false,
      settingsLoading: false,
      operationLogs: [
        {
          operation: '登录',
          module: '系统',
          description: '用户登录系统',
          ip: '192.168.1.100',
          createTime: '2024-01-15 14:30:00',
          status: 'success'
        },
        {
          operation: '查询',
          module: '学生管理',
          description: '查询学生列表',
          ip: '192.168.1.100',
          createTime: '2024-01-15 14:25:00',
          status: 'success'
        },
        {
          operation: '新增',
          module: '课程管理',
          description: '新增课程信息',
          ip: '192.168.1.100',
          createTime: '2024-01-15 14:20:00',
          status: 'success'
        }
      ]
    }
  },
  computed: {
    userInfo() {
      return this.userStore.userInfo
    }
  },
  mounted() {
    this.loadUserSettings()
  },
  methods: {
    getRoleTagType(roleValue) {
      switch (roleValue) {
        case 0: return 'danger'   // 管理员
        case 1: return 'warning'  // 教师
        case 2: return 'primary'  // 学生
        default: return 'info'
      }
    },
    getRoleDescription(roleValue) {
      switch (roleValue) {
        case 0: return '最高权限 - 可管理所有功能'
        case 1: return '教师权限 - 可管理课程和成绩'
        case 2: return '学生权限 - 可查看个人信息'
        default: return '未知权限'
      }
    },
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    async handleChangePassword() {
      try {
        await this.$refs.passwordForm.validate()
        this.passwordLoading = true
        
        const passwordData = {
          oldPwd: this.passwordForm.oldPassword,
          newPwd: this.passwordForm.newPassword
        }
        
        const response = await userApi.changePassword(this.userInfo.hm, passwordData)
        if (response.code === 200) {
          this.$message.success('密码修改成功，请重新登录')
          this.resetPasswordForm()
          // 密码修改成功后，清除登录状态，跳转到登录页
          setTimeout(() => {
            this.userStore.logout()
          }, 1500)
        } else {
          this.$message.error(response.message || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        this.$message.error(error.response?.data?.message || '密码修改失败')
      } finally {
        this.passwordLoading = false
      }
    },
    resetPasswordForm() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      this.$refs.passwordForm?.clearValidate()
    },
    async handleUpdateSettings() {
      try {
        this.settingsLoading = true
        
        // 实际应该调用更新设置API
        setTimeout(() => {
          this.$message.success('设置保存成功')
          this.settingsLoading = false
        }, 1000)
      } catch (error) {
        this.$message.error('保存设置失败')
        this.settingsLoading = false
      }
    },
    loadUserSettings() {
      // 实际应该从API加载用户设置
      this.settingsForm = {
        email: this.userInfo.email || '',
        phone: this.userInfo.phone || '',
        description: this.userInfo.description || ''
      }
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card .profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 20px;
}

.user-name {
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}

.user-role {
  margin-bottom: 20px;
}

.info-list {
  text-align: left;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  font-weight: 500;
}

.value {
  color: #333;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>